#!/bin/sh

#openlookeng install path
install_dir_path=`cat config.txt | sed '/^INSTALL_DIR=/!d;s/.*=//'`
install_dir=${install_dir_path}/openlookeng
#get cn & worker ip from ip.txt
cn_ip=`cat config.txt | sed '/^CN_IP=/!d;s/.*=//'`
worker_ip=`cat config.txt | sed '/^WORKER_IP=/!d;s/.*=//'`
all_ip=`echo "$cn_ip $worker_ip"`
current_relative_path=`dirname $0`
current_path=`cd $current_relative_path;pwd`

#core-site path & hdfs-site path
core_site=`cat config.txt | sed '/^core_site=/!d;s/.*=//'`
hdfs_site=`cat config.txt | sed '/^hdfs_site=/!d;s/.*=//'`

#The number of worker node
node_num=`echo $worker_ip |awk '{print NF}'`

#Judge If this is AA mode
judgeAA()
{
    cn_count=`echo $cn_ip |wc |awk '{print $2}'`
    if [ $cn_count -gt 1 ]
    then
        sed -i "/^hetu.multiple-coordinator.enabled/s#\(hetu.multiple-coordinator.enabled=\).*#\1true#g" ./etc_cn/config.properties
        sed -i "/^hetu.multiple-coordinator.enabled/s#\(hetu.multiple-coordinator.enabled=\).*#\1true#g" ./etc_worker/config.properties
    elif [ $cn_count -eq 1 ]
    then
        sed -i "/^hetu.multiple-coordinator.enabled/s#\(hetu.multiple-coordinator.enabled=\).*#\1false#g" ./etc_cn/config.properties
        sed -i "/^hetu.multiple-coordinator.enabled/s#\(hetu.multiple-coordinator.enabled=\).*#\1false#g" ./etc_worker/config.properties
    else
        echo "There is no CN detected! Exit..."
        exit 1
    fi
}

#Get available mem
getAvaiMem()
{
    array=()
    flag=0
    for ip in $all_ip
    do
        avai_mem_num_01=`ssh root@$ip "free -h |grep -i mem" </dev/null`
        avai_mem_num_02=`echo $avai_mem_num_01 |awk '{print $NF}' |tr -cd [0-9]`
        array[$flag]=$avai_mem_num_02
        flag=$(($flag+1))
    done

    #Get the min avai_mem among all node
    let min=${array[0]}

    for (( i=0;i<${#array[*]};i++))
    do
        [[ ${min} -gt ${array[$i]} ]] && min=${array[$i]}
    done
    avai_mem_num=$min
    return $avai_mem_num

}

##### modify the config.properties file and sync the etc/ to every node #####
modifyConfigProperties()
{

    #Find optimized configuration value
    getAvaiMem
#    avai_mem_num=$?
    #avai_mem_num=`free -h |grep -i mem |awk '{print $NF}' |tr -cd "[0-9]"`
    avai_mem_unit=`free -h |grep -i mem |awk '{print $NF}' |tr -cd "[A-Z]"`
    jvm_mem=`echo "$avai_mem_num*0.8" |bc |awk -F'.' '{print $1}'`
    mem_per_node=`echo "$jvm_mem*0.65" |bc |awk -F'.' '{print $1}'`
    mem_total=`echo "$mem_per_node*$node_num" |bc |awk -F'.' '{print $1}'`
    mem_heap=`echo "$jvm_mem*0.3" |bc |awk -F'.' '{print $1}'`
    discovery_uri=`cat ./config.txt |grep -v '#' |grep "discovery.uri"`
    spill_path=`cat ./config.txt |grep -v '#' |grep "experimental.spiller-spill-path"`
    metastore_uri=`cat ./config.txt |grep -v '#' |grep "hive.metastore.uri"`

    #Optimize the setting file
    etc_list="etc_cn etc_worker"
    for i in $etc_list
    do
        #jvm.config 
        sed -i "/-Xmx/s#\(-Xmx\).*#\1$jvm_mem$avai_mem_unit#g" ./$i/jvm.config
   
        #config.properties
        sed -i "/^query.max-memory/s#\(query.max-memory=\).*#\1$mem_total$avai_mem_unit\B#g" ./$i/config.properties
        sed -i "/^query.max-total-memory/s#\(query.max-total-memory=\).*#\1$mem_total$avai_mem_unit\B#g" ./$i/config.properties
        sed -i "/^query.max-memory-per-node/s#\(query.max-memory-per-node=\).*#\1$mem_per_node$avai_mem_unit\B#g" ./$i/config.properties
        sed -i "/^query.max-total-memory-per-node/s#\(query.max-total-memory-per-node=\).*#\1$mem_per_node$avai_mem_unit\B#g" ./$i/config.properties
        sed -i "/^memory.heap-headroom/s#\(memory.heap-headroom-per-node=\).*#\1$mem_heap$avai_mem_unit\B#g" ./$i/config.properties
        sed -i "/^discovery.uri/s#\(discovery.uri=http://\).*\(:$uri_prot\)#\1$cn_ip\2#g" ./$i/config.properties
        sed -i "/^discovery.uri/s#.*#$discovery_uri#g" ./$i/config.properties
        sed -i "/^experimental.spiller-spill-path/s#.*#$spill_path#g" ./$i/config.properties
       
        #filesystem/hdfs-config-default.properties
        sed -i "/^hdfs.config.resources/s#\(hdfs.config.resources=\).*#\1$core_site,$hdfs_site#g" ./$i/filesystem/hdfs-config-default.properties
 
        #hive.properties
        sed -i "/^hive.metastore.uri/s#.*#$metastore_uri#g" ./$i/catalog/hive.properties
        sed -i "/^hive.config.resources/s#\(hive.config.resources=\).*#\1$core_site,$hdfs_site#g" ./$i/catalog/hive.properties
    done
}

##### modify hetu metastore #####
modifyHetuMetaStore()
{
    grep "^hetu.metastore" config.txt >/dev/null
    if [ $? -eq 0 ];then
        grep "^hetu.metastore" config.txt > ./etc_cn/hetu-metastore.properties
        grep "^hetu.metastore" config.txt > ./etc_worker/hetu-metastore.properties
    else
        find ./etc_cn/ -name hetu-metastore.properties |xargs rm > /dev/null 2>&1
        find ./etc_worker/ -name hetu-metastore.properties |xargs rm > /dev/null 2>&1
    fi
}


##### modify the state-store.properties #####
modifyStateStore()
{
    grep -E "^state-store|^hazelcast.discovery" config.txt >/dev/null
    if [ $? -eq 0 ];then
        grep -E "^state-store|^hazelcast.discovery" config.txt > etc_cn/state-store.properties
        grep -E "^state-store|^hazelcast.discovery" config.txt > etc_worker/state-store.properties
        sed -i '/^hetu.embedded-state-store.enabled/s#\(hetu.embedded-state-store.enabled=\).*#\1true#g' etc_cn/config.properties
        sed -i '/^hetu.embedded-state-store.enabled/s#\(hetu.embedded-state-store.enabled=\).*#\1true#g' etc_worker/config.properties
    else
        find ./etc_cn/ -name state-store.properties |xargs rm > /dev/null 2>&1
        find ./etc_worker/ -name state-store.properties |xargs rm > /dev/null 2>&1
        sed -i '/^hetu.embedded-state-store.enabled/s#\(hetu.embedded-state-store.enabled=\).*#\1false#g' etc_cn/config.properties
        sed -i '/^hetu.embedded-state-store.enabled/s#\(hetu.embedded-state-store.enabled=\).*#\1false#g' etc_worker/config.properties
    fi
}

##### modify the node.properties file and sync the etc/ to every node #####
modifyNodeProperties()
{
    #Create setting file on CN node
    hetu_path=`find $install_dir -maxdepth 1 -type d -name "hetu*"`
    if [ "$hetu_path" = "" ];then
        echo "There is no uncompressed package in $install_dir for CN node. Exit..."
        exit 1
    fi
    #replace_str1=`echo $cn_ip |awk -F'.' '{print $4}'`
    #sed -i "s/\(node.id.*\).../\1$replace_str1/g" ./etc_cn/node.properties
    for etc in etc_cn etc_worker;do
        sed -i "/^node.launcher-log-file/s#\(node.launcher-log-file=\).*#\1${hetu_path}/log/launch.log#g" ./$etc/node.properties
        sed -i "/^node.server-log-file/s#\(node.server-log-file=\).*#\1${hetu_path}/log/server.log#g" ./$etc/node.properties
        sed -i "/^catalog.config-dir/s#\(catalog.config-dir=\).*#\1${hetu_path}/etc/catalog#g" ./$etc/node.properties
        sed -i "/^node.data-dir/s#\(node.data-dir=\).*#\1${hetu_path}/data#g" ./$etc/node.properties
        sed -i "/^plugin.dir/s#\(plugin.dir=\).*#\1${hetu_path}/plugin#g" ./$etc/node.properties
    done

    #Create setting file on cn nodes
    for i in $cn_ip
    do
        hetu_path_cnn=`ssh root@$i find $install_dir -maxdepth 1 -type d -name "hetu*"`
        if [ "$hetu_path_cnn" = "" ];then
            echo "There is no uncompressed package in $install_dir for $i. Exit..."
            exit 1
        fi
        sed -i "/^discovery.uri=/s#\(discovery.uri=http://\).*\(:.*\)#\1$i\2#g"  ./etc_cn/config.properties
        ssh root@$i "rm -rf $hetu_path_cnn/etc"
        scp -r ./etc_cn root@$i:$hetu_path_cnn/etc
    done    

    #Create setting file on worker nodes
    for i in $worker_ip
    do
        hetu_path_wn=`ssh root@$i find $install_dir -maxdepth 1 -type d -name "hetu*"`
        if [ "$hetu_path_wn" = "" ];then
            echo "There is no uncompressed package in $install_dir for $i. Exit..."
            exit 1
        fi
        #replace_str2=`echo $i |awk -F'.' '{print $4}'`
        #sed -i "s/\(node.id.*\).../\1$replace_str2/g" ./etc_worker/node.properties
        ssh root@$i "rm -rf $hetu_path_wn/etc"
        scp -r ./etc_worker root@$i:$hetu_path_wn/etc
    done
}

cpFile()
{
    cp $current_path/launch/start.sh $install_dir
    cp $current_path/launch/stop.sh $install_dir
    cp $current_path/launch/scp_file.sh $install_dir
    cp -r $current_path/etc_cn $install_dir
    cp -r $current_path/etc_worker $install_dir
}

##### Start cluster #####
startCluster()
{
    read -r -p "Do you want to start the cluster now?[y/n]" input
        case $input in
            y)
                echo "Starting the cluster..."
                sh $install_dir/start.sh
                ;;
            n)
                echo
                ;;
        esac
}

echo "+++++ Excuting setting.sh +++++"
judgeAA
getAvaiMem
modifyConfigProperties
modifyHetuMetaStore
modifyStateStore
modifyNodeProperties
cpFile
startCluster
